import React, { Component } from 'react';
import {
    StyleSheet, Text, View, Image, TouchableOpacity,
    ScrollView, KeyboardAvoidingView, Platform, Keyboard, Alert
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { Common } from '../../../component/common/Common.js';
import { Button } from '../../../components/form/button';
import { FormItem } from '../../../components/form/formItem';
import ProductSelect from '../../product/modals/ProductSelect';
import Dictionary from '../../../utils/dictionary';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
import ToastUtil from '../../../utils/toast';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { UpDown } from './_components/UpDown';
import { CURRENCY } from '../../../utils/helper';
import { toggleBtnStyle } from '../create/_common/style';
import moment from 'moment';
import MethodUtil from '../../../utils/MethodUtil';
import { DatePicker } from 'react-native-pickers';
import Utils from '../../../utils/utils';
import { SelectOnffBlock } from "../create/_block/SelectOnffBlock";
import OrderCreateMethods from '../OrderCreateMethods';
import { OriginalAddress } from "../../../component/ui/OriginalAddress";
const scale = GLOBAL.SCALE;
const checkOnImg = require('../../../imgs/checkOn.png');
const checkOffImg = require('../../../imgs/checkOff.png');
let sendData = {};
const priceReg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/;
const quantityReg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,3})?$/;



// tCode        
// 长约->L  	
// 现货 采购/销售->S 
// 代理->A
// 背靠背->C
// 远期->F 
// 长约执行 采购/销售 ->E 

export class ProductTurnForm extends Component {
    static navigationOptions = ({ navigation, navigationOptions }) => {
        let { productList } = navigation.state.params;
        console.log('navigation-9999', navigation)
        return {
            headerTitle: '新增商品',
            headerTintColor: '#272727',
            headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#272727' />,
            headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../imgs/goBackEmpty.png')} />),
            headerTitleStyle: {
                flex: 1,
                textAlign: 'center'
            },
            headerStyle: {
                elevation: 0,
                backgroundColor: '#F5F5F5',
                borderBottomWidth: 0,
            },
        }
    };

    constructor(props) {
        super(props);
        console.log('123-props-商品参数', props.navigation.state.params)
        this.state = {
            goodsModal: false,// 商品数据
            goodsValue: '',
            goodsListVal: [],

            settlementIndex: -1,
            settlementData: [],
            settlementModal: false,
            settlementValue: '',

            baseSettleIndex: -1,//基准月 ....
            baseSettleModal: false,
            baseSettleData: [],


            settlementPriceModal: false,  // 结算价  控制
            settlementPriceData: [],
            settlementPriceIndex: -1,
            settlementPriceValue: '',
            settlementPriceValueOld: '',
            quantityAppointModal: false,  // 品质约定
            quantityAppointData: [],
            quantityAppointIndex: -1,
            quantityAppointValue: '',

            status: 'data',   // 状态 
            editable: true, // 是否能够编辑 true-能编辑  false-不能编辑
            executeEditable: true,
            priceEditable: true,			// 暂定价是否可以编辑
            fixedPriceEditable: true, // 一口价是否可以编辑
            includeNextMonth: false, // 包含下月采购/销售
            priceTypeData: [], // 一口价和暂定价
            productPriceType: '', // 一口价和暂定价商品过滤
            profit: 0, // 闭口的毛利
            modalVisible: false //原产地
        }
        // 展示数据
        this.showData = {
            remainPlanQuantity: 0, // 本月剩余可售/可采量
            longQuantity: 0, // 执行模式-商品总量
            remainLongQuantity: 0, // 执行模式-商品剩余量
            stockQuantity: 0, // 分公司敞口库存
            stockQuantityMax: 0, // 敞口计划量
            suggestedPrice: 0, // 今日现货价
            udPrice: '0',
            purchaseUdPrice: '0',
            saleUdPrice: '0',
            huoIndex: 0,  // 升贴水
            purchaseUdIndex: 0, // 背靠背-采购升贴水
            saleUdIndex: 0, // 背靠背-采购升贴水
        }
        this.isCustom = false; //基准月是否显示
    }

    async componentWillMount() {
        this.currentMonth = moment().format('YYYYMM');
        this.nextMonth = moment().add('months', 1).format('YYYYMM');
        this.initPage();
        await this.initDictionary();
        if (this.editData) {
            this._editInit();
        } else {
            //溢短装率 (现货采购、现货销售、采购转单、销售转单、闭口销售) 默认取5%
            if (this.tCode === 'S' || this.tCode === 'C') {
                sendData.ysPercent = 5;
            }
        }
        this.initPriceType(); // 初始化价格类型
        if (this.tCode == 'E' || this.tCode == 'S') this.initNextMonthQuantity(); // 下月采购量
    }

    componentWillUnmount() {
        this.editData = null;
    }

    // 页面初始化
    initPage = () => {
        let {
            tCode, orderType, periodType, companyId, companyName, editData, longFrameIdArr, frameGoodsList, isZXY,
            companyIdBuy, companyNameBuy, agencyCompanyId, agencyCompanyName, currency, goodsStateList, orderPlanNotCheckFlag, productList, productIndex,
            bidId, isCustIntentionPlan, bidIntentionOrderList, groupOnoff
        } = this.props.navigation.state.params;
        let currentProductList = JSON.parse(JSON.stringify(productList));
        sendData = { orderType, periodType, companyId, companyName };
        this.groupOnoff = groupOnoff || null;
        this.tCode = tCode;
        this.isZXY = isZXY;
        this.orderType = orderType;
        this.editData = editData || null; // 编辑
        this.agencyCompanyId = agencyCompanyId || ''; // 代理需要用到的卖家id
        this.agencyCompanyName = agencyCompanyName || '';
        this.goodsState = editData ? editData.goodsState || '' : ''; // 编辑商品的类型， 如固体、液体
        this.goodsStateList = goodsStateList || [] // 除了当前商品的其他类型
        this.orderPlanNotCheckFlag = orderPlanNotCheckFlag == 1; // 是否是中新油企业
        this.productList = currentProductList;
        this.productIndex = productIndex;
        this.longFrameIdArr = longFrameIdArr || '';
        this.frameGoodsList = frameGoodsList ? JSON.parse(JSON.stringify(frameGoodsList)) : [];
        this.bidId = bidId;
        this.isCustIntentionPlan = isCustIntentionPlan;
        this.bidIntentionOrderList = bidIntentionOrderList;
        if (this.goodsState && this.goodsStateList && this.goodsStateList.length > 0) {
            this.goodsStateList.splice(this.goodsStateList.indexOf(this.goodsState), 1)
        }
        // 判断币种，默认为'元'
        if (currency) {
            this.unit = CURRENCY.getUnit(currency).text;
            this.unitSymbol = CURRENCY.getUnit(currency).label;
        } else {
            this.unit = '元';
            this.unitSymbol = '￥';
        }
        // 背靠背
        if (tCode === 'C') {
            sendData.companyIdBuy = companyIdBuy;
            sendData.companyNameBuy = companyNameBuy;
        }
        // 长约执行
        if (tCode === 'E') this.pushIndex = -1;
    }

    // 编辑回填
    _editInit = async (longFrameData) => {
        console.log('选择商品回填框架longFrameData...', longFrameData, this.editData)
        this.setState({ status: 'loading' })
        let { itemId, goodsName, goodsId, transLevel, quantity, remainQuantity, priceType, purchasePrice, salePrice, barePrice,
            udPrice, priceFormlaName, purchaseUdPrice, saleUdPrice, qualityStd, qualityRemark,
            priceFormlaId, remark, assistQuantity, baseDateSettle, tmpPriceModel, isExistPriceFormula, orderPlanMonth, longItemId,
            bizLineId, bizTeamId, ysPercent, bidOrderId, formulaSettleType, formulaSettleValue, formulaSettleName, formulaCustomValue,
            resourceId, bareUdPrice, rebateId, checkRebateFlag, makePlace, makeAreaId, udPriceOld
        } = longFrameData || this.editData;
        let { quantityAppointData } = this.state;
        let quantityAppointIndex = -1;
        let quantityAppointValue = '';
        let settlementPriceIndex = -1;
        let settlementPriceValue = '';
        // 品质约定
        if (quantityAppointData && quantityAppointData.length > 0) {
            quantityAppointData.forEach((item, index) => {
                if (item.dictKey == qualityStd) {
                    quantityAppointIndex = index;
                    quantityAppointValue = item.dictName;
                    quantityAppointValueOld = item.dictName;
                    sendData.qualityStd = qualityStd
                }
            })
        }
        sendData.ysPercent = ysPercent;
        sendData.itemId = itemId;
        sendData.goodsId = goodsId || '';
        sendData.goodsName = goodsName || '';
        sendData.transLevel = transLevel;
        sendData.quantity = quantity ? quantity.toString() : ''; // 总量
        sendData.remainQuantity = remainQuantity || null; // 可转单量
        sendData.bidOrderId = bidOrderId || null;
        sendData.priceType = priceType; // 价格类型
        sendData.orderPlanMonth = orderPlanMonth == this.nextMonth ? this.nextMonth : this.currentMonth; // 下月采购/销售
        sendData.isExistPriceFormula = isExistPriceFormula; // isExistPriceFormula == 1说明该商品支持暂定价
        sendData.qualityRemark = qualityRemark ? qualityRemark : ''; // 品质约定说明
        sendData.tmpPriceModel = tmpPriceModel || ''; // 是否是一口价变
        sendData.bizLineId = bizLineId; // 编辑回显
        sendData.bizTeamId = bizTeamId; // 编辑回显
        sendData.formulaSettleType = formulaSettleType; //
        sendData.formulaSettleValue = formulaSettleValue;
        sendData.formulaSettleName = formulaSettleName;
        sendData.formulaCustomValue = formulaCustomValue;
        sendData.resourceId = resourceId;
        sendData.bareUdPrice = bareUdPrice;
        sendData.rebateId = rebateId;
        sendData.checkRebateFlag = checkRebateFlag;
        sendData.makePlace = makePlace;
        sendData.makeAreaId = makeAreaId;
        sendData.udPriceOld = udPriceOld;
        if (this.tCode === 'C') {
            sendData.purchasePrice = purchasePrice ? purchasePrice.toString() : ''; // 采购价
            sendData.salePrice = salePrice ? salePrice.toString() : ''; // 销售价
            if (purchaseUdPrice) this.showData.purchaseUdIndex = purchaseUdPrice >= 0 ? 0 : 1; // 采购升贴水
            this.showData.purchaseUdPrice = purchaseUdPrice ? Math.abs(purchaseUdPrice).toString() : '';
            if (saleUdPrice) this.showData.saleUdIndex = saleUdPrice >= 0 ? 0 : 1;  // 销售升贴水
            this.showData.saleUdPrice = saleUdPrice ? Math.abs(saleUdPrice).toString() : '';
        } else {
            sendData.barePrice = barePrice ? barePrice.toString() : '';
        }
        if (this.tCode === 'F') sendData.remark = remark; // 远期采购说明
        if (this.tCode != 'C' && priceType == 2) {
            if (udPrice) this.showData.huoIndex = udPrice >= 0 ? 0 : 1;
            this.showData.udPrice = udPrice ? Math.abs(udPrice).toString() : '0';
        }
        let settlementPriceData = await this._settlementPriceData() || []; // 结算价-公式
        if (this.tCode == 'E') {
            sendData.longItemId = longItemId;
            this.formDisabled(longFrameData || this.editData); // 长约执行需要判断部分表单是否禁用
        }
        if (sendData.goodsId) {
            await this.getGoodsQuantity(); // 获取数量
            await this.getLatestPrice(); // 获取今日现货价
        }
        // 长约执行可能存在没有goodsId回填的情况
        if (goodsId) {
            if (settlementPriceData && settlementPriceData.length > 0) {
                settlementPriceData && settlementPriceData.forEach((item, index) => {
                    if (item.formulaId == priceFormlaId) {
                        settlementPriceIndex = index;
                        sendData.priceFormlaId = priceFormlaId;
                        sendData.priceFormlaName = item.formulaName;
                        settlementPriceValue = item.formulaName;
                    }
                })
            }
        } else {
            sendData.priceFormlaId = priceFormlaId || '';
            sendData.priceFormlaName = priceFormlaName || '';
            settlementPriceValue = priceFormlaName || '';
        }

        console.log('sendData-999', sendData)
        this.calculateProfit();
        //是否有 基准月,基准日
        this._getBase();
        this.setState({ goodsValue: goodsName, quantityAppointValue, quantityAppointIndex, settlementPriceIndex, settlementPriceValue, settlementPriceValueOld: settlementPriceValue, status: 'data' })
    }

    // 一口价暂定价限制
    /** 
     * 新增 
     * 第一个商品：
     *      1. 获取所有商品 productPriceType = ''
     *      2. 显示所有价格类型 allPriceTypeData
     * 第n个商品
     *      1. 根据第一个商品的价格类型获取商品数据
     *      2. 价格类型只显示一个，不可切换
     * 
     * 编辑
     * 第一个商品：
     *      1. 获取所有商品 productPriceType = ''
     *      2. 获取当前商品支持的价格类型
     * 第n个商品
     *      1. 根据第一个商品的价格类型获取商品数据
     *      2. 价格类型只显示一个，不可切换
    */
    initPriceType = async () => {
        let productPriceType = ''; // 选择全部商品
        let priceTypeData = []; // 过滤后的价格类型
        if (this.tCode == 'E') {
            this.setState({ productPriceType: this.frameGoodsList[0].priceType || '' })
            return
        }
        if (this.productIndex == 0) {
            priceTypeData = this.editData ? await this.getCurrentPriceType() : this.allPriceTypeData;
            sendData.priceType = this.editData ? sendData.priceType : priceTypeData[0].dictKey || '1'
        }
        if (this.productIndex > 0) {
            productPriceType = this.productList[0].priceType || '';
            sendData.priceType = this.editData ? sendData.priceType : productPriceType;
            this.allPriceTypeData.forEach(item => {
                if (item.dictKey == productPriceType) { priceTypeData.push(item) }
            })
        }
        this.setState({ priceTypeData, productPriceType })
    }

    // 获取当前商品支持的价格类型 
    getCurrentPriceType = async () => {
        let currentPriceType = [];
        // isExistPriceFormula == 1 支持暂定价，否则只支持一口价
        if (sendData.isExistPriceFormula == 1) {
            currentPriceType = this.allPriceTypeData
        } else {
            currentPriceType.push(this.allPriceTypeData[0]);
        }
        return currentPriceType
    }

    // 一口价暂定价限制：选择的商品只支持一口价或暂定价
    getProductPriceType = async () => {
        // 新增或者编辑第一个商品时需要控制
        if (this.productIndex == 0) {
            let priceTypeData = await this.getCurrentPriceType();
            sendData.priceType = priceTypeData.length > 1 ? sendData.priceType : priceTypeData[0].dictKey;
            this.calculateProfit();
            this.setState({ priceTypeData })
        }
    }

    // 下月采购/销售量限制：新增的商品都按照第一个商品来
    initNextMonthQuantity = async () => {
        if (this.productIndex == 0) {
            sendData.orderPlanMonth = this.editData && this.editData.orderPlanMonth ? sendData.orderPlanMonth : this.currentMonth;
        }
        if (this.productIndex > 0) {
            sendData.orderPlanMonth = this.productList[0].orderPlanMonth || this.currentMonth;
        }
        this.setState({
            includeNextMonth: sendData.orderPlanMonth == this.nextMonth
        })
    }

    /**
     * 选择下月采购/销售量
     * - 第一个商品切换，需要判断其他商品是否支持下月，支持就切换，不支持提示
     * - 除了第一个商品，其他商品都无法切换
     */
    selectNextMonthQuantity = async () => {
        Keyboard.dismiss();
        if (this.productIndex > 0) return
        let nextMonthFlag = !this.state.includeNextMonth;
        let newProductList = [];
        // 循环所有的商品，判断是否支持下月采购/销售量
        if (this.productList.length > 1) {
            this.setState({ status: 'loading' })
            Promise.all(this.getPromise(nextMonthFlag)).then(allData => {
                for (let i = 0; i < this.productList.length; i++) {
                    if (i == 0 || (allData[i].remainPlanQuantity && allData[i].remainPlanQuantity >= this.productList[i].quantity)) newProductList.push(this.productList[i])
                    if (i == this.productList.length - 1) this.checkProductList(newProductList, nextMonthFlag);
                }
                this.setState({ status: 'data' })
            })
        } else {
            sendData.orderPlanMonth = nextMonthFlag ? this.nextMonth : this.currentMonth;
            this.getGoodsQuantity();
            this.setState({ includeNextMonth: nextMonthFlag })
        }
    }

    getPromise = (nextMonthFlag) => {
        let promises = this.productList.map((item, index) => {
            return (this.getGoodsQuantity(index, index == 0 ? sendData : item, nextMonthFlag ? this.nextMonth : this.currentMonth))
        })
        return promises
    }

    checkProductList = (newProductList, nextMonthFlag) => {
        newProductList.forEach(item => { item.orderPlanMonth = nextMonthFlag ? this.nextMonth : this.currentMonth })
        if (newProductList.length == this.productList.length) {
            this.productList = newProductList;
            sendData.orderPlanMonth = nextMonthFlag ? this.nextMonth : this.currentMonth;
            this.setState({ includeNextMonth: nextMonthFlag })
        } else {
            this.confirmToggleNextMonth(newProductList, nextMonthFlag)
        }
    }

    confirmToggleNextMonth = (productList, nextMonthFlag) => {
        Alert.alert('提示', `切换计划量可能会导致部分商品计划量不足而无法提交，请谨慎操作！`, [
            {
                text: '确认', onPress: () => {
                    this.productList = productList;
                    sendData.orderPlanMonth = nextMonthFlag ? this.nextMonth : this.currentMonth;
                    this.getGoodsQuantity();
                    this.setState({ includeNextMonth: nextMonthFlag })
                }
            },
            {
                text: '取消', onPress: () => {
                    console.log(sendData, this.productList)
                }
            },
        ]);
    }

    // 长约执行需要判断部分表单是否禁用
    formDisabled = (executeInfo) => {
        let editable = false;
        let priceEditable = true;
        let executeEditable = true;
        let fixedPriceEditable = true;
        // 如果价格填写了，则不可修改	
        if (executeInfo.barePrice) priceEditable = false
        // 如果结算价、结算公式、升贴水都填写了，则不可编辑，否则这三项可以编辑
        if (executeInfo.udPrice && executeInfo.tempPriceFormulaId && executeInfo.priceFormlaId) {
            executeEditable = false;
        } else {
            priceEditable = true;
        }
        fixedPriceEditable = true; // 没有一口价，暂时一口价都可以编辑
        this.setState({
            priceEditable, executeEditable, editable, fixedPriceEditable
        })
    }

    //数据字典-初始化
    async initDictionary() {
        this.setState({ status: 'loading' })
        let quantityAppointData = await Dictionary.get('GOODS_QUALITY_STANDARD');
        let settlementData = await Dictionary.get('BASE_DATE_SETTLE');
        let priceTypeData = await Dictionary.get('EC_PRICE_TYPE');
        //let ysPercentData = await Dictionary.get('YS_PERCENT_TYPE');//溢短装率
        this.allPriceTypeData = priceTypeData;
        this.setState({
            quantityAppointData: quantityAppointData || [],
            settlementData: settlementData || [],
            priceTypeData: priceTypeData || [],
            status: 'data'
        });
    }

    //结算价公式 - 数据 
    async  _settlementPriceData() {
        if (sendData.goodsId) {
            this.setState({
                status: 'loading'
            })
            let responseData = await HTTP.POST(API_GENERATE(API.GET_PRICE), {
                goodsId: sendData.goodsId,
                orderType: sendData.orderType
            });
            if (!responseData) return resolve()
            responseData.map((item, index) => {
                item.dictName = item.formulaName;
            });
            this.setState({
                status: 'data',
                settlementPriceData: responseData,
                settlementPriceValue: sendData.priceFormlaName,
                settlementPriceValueOld: sendData.priceFormlaName
            })
            return new Promise((resolve, reject) => {
                resolve(responseData);
            })
        }
    }

    // 计划量控制
    checkPlanQuantity = () => {
        let { isUnite } = this.props.navigation.state.params;
        // 长约执行采购 中新油的企业不需要控
        if (this.tCode == 'E' && this.orderPlanNotCheckFlag) return
        if (this.tCode == 'E') {
            // 下面情况需要计划管控 isUnite 0-自营  1-统销
            // isUnite == 0  orderType == 'P'
            // isUnite == 0  orderType == 'S'
            // isUnite == 1  orderType == 'S'
            if ((sendData.orderType == 'P' && isUnite == '0') || (sendData.orderType == 'S' && (isUnite == '0' || isUnite == '1'))) {
                if (!this.showData.remainPlanQuantity && this.showData.remainPlanQuantity != 0) {
                    ToastUtil.showWarning('暂无提报计划量，请提报后提交', 1500);
                    return true
                }
                if ((this.showData.remainPlanQuantity || this.showData.remainPlanQuantity == 0) && sendData.quantity && (parseFloat(sendData.quantity) > parseFloat(this.showData.remainPlanQuantity))) {
                    ToastUtil.showWarning(`${sendData.orderType == 'P' ? '采购量' : '销售量'}大于计划量，请调整后提交`, 1500);
                    return true
                }
            }
        }
    }

    // 当前交易数量+分公司敞口库存 必须小于等于敞口上限（仅采购需要控制）
    checkInventory = () => {
        // isUnite = 0 库存，执行量
        // isUnite = 1
        this.calculateProfit();
        let { isUnite } = this.props.navigation.state.params;
        if (this.tCode == 'S' || this.tCode == 'E') {
            let { stockQuantity, stockQuantityMax, longQuantity } = this.showData;
            if (sendData.orderType == 'S' && this.tCode == 'E' && parseFloat(sendData.quantity) > parseFloat(longQuantity)) {
                ToastUtil.showWarning('数量已超出框架剩余量', 1500);
                return true
            }
            // 延期上线
            // if (sendData.orderType == 'P' && stockQuantityMax && (parseFloat(sendData.quantity) + parseFloat(stockQuantity || 0)) > parseFloat(stockQuantityMax || 0)) {
            //   ToastUtil.showWarning('数量+库存须小于等于库存上限', 1500);
            //   return true
            // }
        }
    }

    // 获取商品数量和库存
    getGoodsQuantity = async (index, item, month) => {
        if (this.tCode != 'E' && this.tCode != 'S') return
        return new Promise(async resolve => {
            let { isUnite } = this.props.navigation.state.params;
            let goodsId = item ? item.goodsId : sendData.goodsId;
            if (!goodsId) return;
            let params = {
                orderType: sendData.orderType,
                isUnite: parseFloat(isUnite),
                orderPlanMonth: month ? month : sendData.orderPlanMonth,
                goodsId,
                companyId: sendData.companyId
            }
            if (this.tCode == 'E') {
                params.orderId = this.longFrameIdArr || '';
                params.itemId = sendData.longItemId;
            }
            let url = this.tCode == 'E' ? API.GET_FRAME_GOODS_QUANTITY : API.GET_GOODS_QUANTITY;
            let res = await HTTP.POST(API_GENERATE(url), params);
            if (!res) return
            if (!item || (item && index == 0)) {
                this.showData.remainPlanQuantity = res.remainPlanQuantity; // 计划量
                this.showData.stockQuantity = res.stockQuantity; // 分公司敞口库存
                this.showData.stockQuantityMax = res.stockQuantityMax; // 敞口上限
                this.showData.longQuantity = res.longQuantity; // 长约总量
                this.showData.remainLongQuantity = res.remainLongQuantity; // 剩余量
                this.setState({ status: 'data' }, () => {
                    if (!item) this.checkPlanQuantity()
                })
            }
            resolve(res)
        })
    }

    // 今日现货价
    async getLatestPrice() {
        let responseData = await HTTP.POST(API_GENERATE(API.GET_LATEST_PRICE), { goodsId: sendData.goodsId });
        if (responseData) {
            let { suggestedPrice } = responseData;
            this.showData.suggestedPrice = suggestedPrice;
            sendData.suggestedPrice = suggestedPrice || 0;
            this.setState({
                ls: true
            })
        }
    }

    // 获取商品参数
    _getGoodsParams = () => {
        let { productPriceType } = this.state;
        let params = {};
        let { creditLevelBuy, creditLevelSell, bidOrderIds } = this.props.navigation.state.params || {};
        let creditLevel = '2';
        if (creditLevelBuy == '1' || creditLevelSell == '1') {
            creditLevel = '1';
        }
        if (this.bidId) {
            params = {
                bidId: this.bidId,
                goodsStateList: this.goodsStateList,
                goodsState: this.goodsState,
                orderType: sendData.orderType,
                priceType: productPriceType,
                isCustIntentionPlan: this.isCustIntentionPlan,
                bidIntentionOrderList: this.bidIntentionOrderList,
                creditLevel,
                bidOrderIds
            };
        } else {
            params = {
                priceType: productPriceType,
                goodsState: this.goodsState,
                goodsStateList: this.goodsStateList,
                orderType: sendData.orderType,
                bizMode: 0, // 敞口-0  闭口-1
                creditLevel
            };
        }
        if (this.tCode == 'C') {
            // 背靠背模式需要选择客户和供应商的商品
            params.companyIdList = [sendData.companyId, sendData.companyIdBuy];
            params.bizMode = 1;
            params.orderType = '';
        } else if (this.tCode == 'A') {
            params.companyIdList = [this.agencyCompanyId, sendData.companyId]
        } else {
            params.companyId = sendData.companyId
        }
        if (this.tCode == 'E') {
            params = {
                orderId: this.longFrameIdArr || '',
                goodsState: this.goodsState,
                goodsStateList: this.goodsStateList,
                creditLevel
            }
        }
        return params;
    }

    // 点击选择商品
    selectProduct = () => {
        Keyboard.dismiss();
        this.setState({ goodsModal: true })
    }

    //商品取消按钮
    _cancelPress = () => {
        this.setState({ goodsModal: false })
    }

    // 选择商品
    _confirmPress = (data) => {
        console.log('商品回调-123', data);
        if (data.length > 0) {
            let _goods = data[0];
            let _goodsItem = _goods.goodsItem || {};
            this.setState({
                goodsModal: false,
                goodsValue: _goods.goodsName,
            }, async () => {
                console.log('data', data)
                let lastGoodsId = sendData.goodsId;
                if (lastGoodsId == _goods.goodsId) return;
                sendData.bizTeamId = _goodsItem.bizTeamId;
                sendData.bizLineId = _goodsItem.bizLineId;
                sendData.goodsId = _goods.goodsId;
                sendData.goodsName = _goods.goodsName;
                sendData.transLevel = _goodsItem.transLevel;
                sendData.goodsState = _goods.goodsState || '';
                sendData.isExistPriceFormula = _goods.isExistPriceFormula ? _goods.isExistPriceFormula : sendData.isExistPriceFormula
                sendData.barePrice = _goodsItem.barePrice;
                //sendData.price = _goodsItem.price; // 赋值没用 后面计算完之后会重新覆盖
                sendData.quantity = _goodsItem.quantity;
                sendData.remainQuantity = _goodsItem.remainQuantity;
                sendData.bidOrderId = _goodsItem.bidOrderId;
                sendData.resourceId = _goodsItem.resourceId;
                this.showData.bidQuantity = _goodsItem.bidQuantity;//可下单量
                this.showData.remainQuantity = _goodsItem.remainQuantity; //剩余量'
                sendData.priceType = _goodsItem.priceType || 1;
                sendData.priceFormlaId = _goodsItem.priceFormlaId;// 暂定价 - 结算公式 id
                sendData.priceFormlaName = _goodsItem.priceFormlaName;// 暂定价 - 结算公式 name
                if (typeof _goodsItem.udPrice === 'number' && !isNaN(_goodsItem.udPrice)) {
                    this.showData.huoIndex = _goodsItem.udPrice >= 0 ? 0 : 1;
                    this.showData.udPrice = Math.abs(_goodsItem.udPrice);
                    sendData.udPrice = _goodsItem.udPrice;
                    sendData.bareUdPrice = _goodsItem.bareUdPrice;
                    sendData.udPriceOld = this.showData.udPrice;
                }
                await this.getGoodsQuantity();//获取商品数量和库存
                await this._settlementPriceData(); //结算价公式 - 数据 
                this.getLatestPrice(); //今日现货价
                //this.getProductPriceType();//一口价暂定价限制：选择的商品只支持一口价或暂定价
                this.clearPriceFormlaData();// 切换商品 判断是否清空结算公式
                this._getBase();

            })
        } else {
            this.setState({ goodsModal: false })
        }
    }

    // 切换商品 判断是否清空结算公式
    clearPriceFormlaData = () => {
        let { settlementPriceData } = this.state;
        if (settlementPriceData && settlementPriceData.length > 0 && this.state.executeEditable) {
            let formulaFlag = false;
            let formulaIndex = -1;
            settlementPriceData.forEach((item, index) => {
                if (item.formulaId == sendData.priceFormlaId) {
                    formulaFlag = true;
                    formulaIndex = index;
                }
            })
            if (formulaFlag) {
                this.setState({ settlementPriceIndex: formulaIndex })
            } else {
                sendData.priceFormlaId = null;
                sendData.priceFormlaName = null;
                this.setState({
                    settlementPriceIndex: -1,
                    settlementPriceValue: '',
                    settlementPriceValueOld: ''
                })
            }
        }
    }

    //打开模态框
    openModal = (obj, index) => {
        var open = true;
        for (key in obj) {
            obj[key] = true;
            if (key == 'settlementPriceModal') {
                open = this.state.executeEditable;
                if (!sendData.goodsId) {
                    open = false;
                    ToastUtil.showWarning('请先选择商品');
                }
            } else if (key == 'baseSettleModal') {
                open = true;
            } else {
                open = this.state.editable
            }
        }
        if (open) {
            this.setState(obj);
        }
    }

    // 选择结算价（公式）
    _settlementPriceCallBack = (index) => {
        //切换时 清空 结算方式
        this._clearDay('1');
        this.setState({
            settlementPriceModal: false,
            settlementPriceValue: this.state.settlementPriceData[index].formulaName,
            settlementPriceIndex: index
        }, () => {
            sendData.priceFormlaId = this.state.settlementPriceData[index].formulaId;
            sendData.priceFormlaName = this.state.settlementPriceData[index].formulaName;
            this._getBase();
        })
    }

    // 选择品质约定
    _quantityAppointCallBack = (index) => {
        sendData.qualityStd = this.state.quantityAppointData[index].dictKey;
        this.setState({
            quantityAppointModal: false,
            quantityAppointValue: this.state.quantityAppointData[index].dictName,
            quantityAppointIndex: index
        })
    }

    //价格 - 一口价/暂定价 - 输入
    _getPrice = (str) => {
        if (this.tCode === 'C') {
            sendData.purchasePrice = str;
            this.calculateProfit();
        } else {
            sendData.barePrice = str;
        }
    }

    // 选择溢短装率
    _ysPercentCallBack = (value) => {
        sendData.ysPercent = value;
    }

    //价格 - 一口价/暂定价 - 输入 - 销售
    _getPriceSell = (str) => {
        sendData.salePrice = str;
        this.calculateProfit();
    }

    //品质说明 - 输入
    _quantityAppoint(str) {
        sendData.qualityRemark = str;
    }

    //总量 -  输入
    _allQuantity = (str) => {
        sendData.quantity = str;
        this.calculateProfit();
    }

    // 下月采购量
    // _nextMonthQuantity (str) {
    //   sendData.nextQuantity = str;
    // }

    //远期采购说明 - 输入
    _remark = (str) => {
        sendData.remark = str;
    }

    // 升贴水 回调函数
    _upDownFn = (options) => {
        if (this.tCode === 'C') {
            this.showData.purchaseUdPrice = options.value;
            this.showData.purchaseUdIndex = options.selectIndex;
        } else if (this.state.executeEditable) {
            this.showData.udPrice = options.value;
            this.showData.huoIndex = options.selectIndex;
        }
        this.calculateProfit();
        this.setState({
            ls: true
        })
    }
    // 升贴水(客户) 回调函数
    _upDownFnSell = (options) => {
        this.showData.saleUdPrice = options.value;
        this.showData.saleUdIndex = options.selectIndex;
        this.calculateProfit();
        this.setState({
            ls: true
        })
    }

    // 关闭弹框
    _closeModal = (obj) => {
        for (key in obj) {
            obj[key] = false;
        }
        this.setState(obj);
    }

    // 表单验证
    verifyReturn = () => {
        let { creditLevelBuy, creditLevelSell } = this.props.navigation.state.params || {};
        let { includeNextMonth, profit } = this.state;
        let { quantity } = this.showData;
        let isTempPrice = sendData.priceType == '2'; // 是否是暂定价
        let priceTypeText = isTempPrice ? '暂定价' : '一口价';
        let quantityTitle = sendData.orderType == 'P' ? '采购' : '销售';
        if (!sendData.goodsId) {
            ToastUtil.showWarning('请选择商品');
            return
        }
        let isIdentical = false;
        if (this.productList && this.productList.length) {
            this.productList.forEach((item, index) => {
                if (this.productIndex != index && item.goodsId == sendData.goodsId) {
                    isIdentical = true;
                }
            })
        }
        if (isIdentical) {
            ToastUtil.showWarning(`商品信息${sendData.goodsName}重复添加！`);
            return
        }
        if ((creditLevelBuy == "1" || creditLevelSell == "1") && sendData.transLevel == 1 && sendData.priceType == "2") {
            ToastUtil.showWarning(`企业评级过低,不支持做该商品暂定价,请重新选择`);
            return
        }
        if (!sendData.quantity) {
            ToastUtil.showWarning(`请输入${quantityTitle}量`);
            return
        }
        if (sendData.quantity && sendData.quantity <= 0) {
            ToastUtil.showWarning(`数量必须大于0`);
            return
        }
        if (!quantityReg.test(sendData.quantity)) {
            ToastUtil.showWarning(`请输入正确的数量(最多3位小数)`);
            return
        }
        if (this.tCode == 'E' && this.showData.remainLongQuantity && sendData.quantity > this.showData.remainLongQuantity) {
            ToastUtil.showWarning(`数量已超出剩余量`);
            return
        }
        if (sendData.quantity > sendData.remainQuantity) {
            ToastUtil.showWarning(`数量不能大于剩余可转单量`);
            return
        }
        // if (sendData.quantity > quantity) {
        //   ToastUtil.showWarning(`数量已超出可下单量`);
        //   return
        // }
        //优惠价格
        if (OrderCreateMethods._rebateValidation(sendData)) {
            ToastUtil.showWarning(`请输入优惠价格`);
            return;
        }
        // 计划量管控
        if (this.checkPlanQuantity()) return;
        // 库存管控
        if (this.checkInventory()) return;
        if (this.tCode == 'C') {
            // 背靠背模式验证
            if (!sendData.purchasePrice) {
                ToastUtil.showWarning(`请输入采购${priceTypeText}`);
                return
            } else if (sendData.purchasePrice && sendData.purchasePrice <= 0) {
                ToastUtil.showWarning(`采购${priceTypeText}必须大于0`);
                return
            } else if (!priceReg.test(sendData.purchasePrice)) {
                ToastUtil.showWarning(`请输入正确的采购${priceTypeText}(最多2位小数)`);
                return
            } else if (!sendData.salePrice) {
                ToastUtil.showWarning(`请输入销售${priceTypeText}`);
                return
            } else if (sendData.salePrice && sendData.salePrice <= 0) {
                ToastUtil.showWarning(`销售${priceTypeText}必须大于0`);
                return
            } else if (!priceReg.test(sendData.salePrice)) {
                ToastUtil.showWarning(`请输入正确的销售${priceTypeText}(最多2位小数)`);
                return
            } else if (profit < 0) {
                ToastUtil.showWarning(`毛利须大于等于0`);
                return
            } else if (isTempPrice && !this.showData.purchaseUdPrice) {
                ToastUtil.showWarning('请输入采购升贴水');
                return
            } else if (isTempPrice && !this.showData.saleUdPrice) {
                ToastUtil.showWarning('请输入销售升贴水');
                return
            } else if (isTempPrice && !sendData.priceFormlaId) {
                ToastUtil.showWarning('请选择结算公式');
                return
            }
        }
        if (this.tCode != 'C') {
            // 其他模式验证
            if (this.tCode != 'L' && !sendData.barePrice) {
                ToastUtil.showWarning(isTempPrice ? '请输入暂定价' : '请输入一口价');
                return
            } else if (sendData.barePrice && sendData.barePrice <= 0) {
                ToastUtil.showWarning(isTempPrice ? '暂定价必须大于0' : '一口价必须大于0');
                return
            } else if (!priceReg.test(sendData.barePrice)) {
                ToastUtil.showWarning(`请输入正确的${priceTypeText}(最多2位小数)`);
                return
            } else if (this.tCode != 'L' && isTempPrice && !sendData.priceFormlaId) {
                ToastUtil.showWarning('请选择结算公式');
                return
            } else if (this.tCode != 'L' && isTempPrice && !this.showData.udPrice) {
                ToastUtil.showWarning('请输入升贴水');
                return
            }
        }
        if (this.tCode == 'F' && !sendData.remark) {
            ToastUtil.showWarning(sendData.orderType == 'P' ? '请输入远期采购说明' : '请输入远期销售说明');
            return
        }
        if (!sendData.qualityStd) {
            ToastUtil.showWarning('请选择品质约定');
            return
        }
        if (sendData.qualityStd == '3' && !sendData.qualityRemark) {
            ToastUtil.showWarning('请输入品质说明');
            return
        }
        if (sendData.ysPercent === '' || sendData.ysPercent === null || sendData.ysPercent === undefined) {
            ToastUtil.showWarning('请输入溢短装率');
            return
        } else if (sendData.ysPercent < 0 || sendData.ysPercent > 20) {
            ToastUtil.showWarning('请输入大于等于0且小于等于20的数字');
            return
        }
        if (isTempPrice) {
            if (this.isCustom && !sendData.formulaCustomValue) {
                ToastUtil.showWarning(`请选择自定义${sendData.formulaSettleType == 'BASE_DATE' ? '日期' : '月份'}`);
                return
            }
            if (!sendData.formulaSettleValue) {
                ToastUtil.showWarning(`请选择${sendData.formulaSettleType == 'BASE_DATE' ? '基准日' : '基准月'}`);
                return
            }
        }
        if (!sendData.makeAreaId) {
            ToastUtil.showWarning('请选择原产地');
            return
        }



        return true
    }

    // 保存
    save = async () => {
        if (!this.verifyReturn()) return;
        Keyboard.dismiss();
        this.productList[this.productIndex] = this.processData(sendData);
        this.props.navigation.state.params.callBack(this.productList);
        this.props.navigation.goBack();
    }

    // 数据处理
    processData = (data) => {
        // 判断升贴水是正还是负
        if (this.tCode == 'C') {
            data.purchaseUdPrice = data.priceType == 2 && this.showData.purchaseUdPrice ? (this.showData.purchaseUdIndex == 0 ? this.showData.purchaseUdPrice : -this.showData.purchaseUdPrice) : '';
            data.saleUdPrice = data.priceType == 2 && this.showData.saleUdPrice ? (this.showData.saleUdIndex == 0 ? this.showData.saleUdPrice : -this.showData.saleUdPrice) : '';
        } else {
            data.udPrice = data.priceType == 2 && this.showData.udPrice ? (this.showData.huoIndex == 0 ? this.showData.udPrice : -this.showData.udPrice) : 0;
        }
        if (data.priceType != 2) {
            data.priceFormlaId = null;
        }
        return data;
    }

    _renderProductCount = () => {
        let isBuyer = sendData.orderType == 'P';
        let buyerOrSellerText = isBuyer ? '采购' : '销售';
        let { goodsValue, includeNextMonth } = this.state;
        let month = includeNextMonth ? '下月' : '当月';
        let planText = isBuyer ? `${month}剩余可采计划量` : `${month}剩余可销计划量`;
        let { longQuantity, remainLongQuantity, remainPlanQuantity, stockQuantity, stockQuantityMax, bidQuantity, remainQuantity } = this.showData;
        if (this.tCode == 'E') {
            // 长约采购/销售执行
            return (
                <View style={styles.infoWrap}>
                    <View><Text style={styles.info}>{planText}{remainPlanQuantity || '--'}吨</Text></View>
                    <View>
                        <Text style={styles.info}>分公司敞口库存{stockQuantity || '--'}吨
              {
                                isBuyer ? <Text style={styles.info}>，敞口上限{stockQuantityMax || '--'}吨</Text> : ''
                            }
                        </Text>

                    </View>

                    <View>
                        <Text style={styles.info}>长约总量{longQuantity || '--'}吨
              <Text style={styles.info}>，剩余量{remainLongQuantity || '--'}吨</Text>
                        </Text>
                    </View>
                </View>
            )
        } else if (this.tCode == 'S') {
            // 采购/销售现货 || 采购远期/销售成交
            return (
                <View style={styles.infoWrap}>
                    {/* <View style={{ flexDirection: 'row' }}>
            <Text style={styles.info}>客户采购量{bidQuantity || '--'},</Text>
            <Text style={styles.info}>可下单量{remainQuantity || '--'}</Text>
          </View> */}
                    {/* <View><Text style={styles.info}>{planText}{remainPlanQuantity || '--'}吨</Text></View> */}
                    <View>
                        <Text style={styles.info}>分公司敞口库存{stockQuantity || '--'}吨
              {
                                isBuyer ? <Text style={styles.info}>，敞口上限{stockQuantityMax || '--'}吨</Text> : ''
                            }
                        </Text>
                    </View>
                </View>
            )
        }
    }

    getQuantityText = (month) => {
        if (this.tCode == 'S' || this.tCode == 'E') {
            let monthText = month || '';
            return sendData.orderType == 'P' ? '采购量' + monthText : '销售量' + monthText;
        } else {
            return '数量'
        }
    }

    // 切换价格类型
    togglePrice = (dictKey) => {
        Keyboard.dismiss();
        if (sendData.priceType == dictKey) return
        /**
         * 如果是编辑第一个商品并且总共有不止一个商品，需要判断后面的商品是否支持该价格类型
         * 所有商品都支持一口价，只有切换暂定价需要判断
         * 支持->全部都切换到该价格类型
         * 不支持->弹出提示，确认切换会删除其他商品
         */
        if (this.productIndex == 0 && this.productList.length > 1) {
            let newProductList = [];
            this.productList.forEach((item, index) => {
                if (dictKey == '1') {
                    // 所有商品都切换到一口价
                    this.productList[index].priceType = dictKey;
                    sendData.priceType = dictKey;
                    this.calculateProfit();
                } else {
                    // 获取第一个和其他支持暂定价的商品
                    if (index == 0 || item.isExistPriceFormula == 1) {
                        let productItem = item;
                        productItem.priceType = dictKey;
                        newProductList.push(productItem);
                    }
                }
            })
            // 如果长度不一致，说明有的商品不支持暂定价
            if (dictKey == '2') {
                if (newProductList.length == this.productList.length) {
                    sendData.priceType = dictKey;
                    this.productList.forEach((item, index) => { this.productList[index].priceType = dictKey });
                    this.calculateProfit();
                } else {
                    this.confirmTogglePrice(newProductList, dictKey);
                }
            }
        } else {
            sendData.priceType = dictKey;
            this.calculateProfit();
        }
        //切换时 清空 结算公式   
        sendData.priceFormlaId = null;
        sendData.priceFormlaName = null;
        //切换时 清空 结算方式
        this._clearDay(dictKey);
        //如果是暂定价 清空优惠价 相关字段
        if (dictKey == '2') {
            sendData.isPromotion = null;
            OrderCreateMethods._callRebateClear(sendData);
        }
        this.setState({ status: 'data', settlementPriceValue: '', settlementPriceIndex: -1, baseSettleIndex: -1 })
    }

    confirmTogglePrice = (productList, priceType) => {
        Alert.alert('提示', `切换价格方式会造成其他不支持该类价格的商品信息数据丢失，请谨慎操作！`, [
            {
                text: '确认', onPress: () => {
                    sendData.priceType = priceType;
                    this.productList = productList;
                    this.calculateProfit();
                    this.setState({ status: 'data' })
                }
            },
            {
                text: '取消', onPress: () => {
                    console.log(sendData)
                }
            },
        ]);
    }

    _renderSwitchWrap = () => {
        let { priceTypeData } = this.state;
        //资源转订单 - 过滤切换
        let lspriceTypeData = [];
        priceTypeData = priceTypeData && priceTypeData.length && priceTypeData.forEach(item => {
            if (item.dictKey == sendData.priceType) {
                lspriceTypeData.push(item);
            }
        })
        priceTypeData = lspriceTypeData;
        return (
            <View>
                <FormItem required={true} rightContent={
                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                        {priceTypeData && priceTypeData.map((item, index) => {
                            return (
                                <TouchableOpacity activeOpacity={.8} key={index} onPress={() => { this.togglePrice(item.dictKey) }} >
                                    <Text style={[sendData.priceType == item.dictKey ? toggleBtnStyle.checkedText : toggleBtnStyle.unCheckText, { marginLeft: 8 * scale, marginRight: 0, width: 70 * scale }]}>{item.dictName}</Text>
                                </TouchableOpacity>
                            )
                        })
                        }
                    </View>
                } label='价格' />
            </View>
        )
    }

    //今日现货价
    _renderTodayPrice = () => {
        let { suggestedPrice } = this.showData;
        return (
            <View style={{ paddingLeft: 22 * scale, paddingRight: 22 * scale }}>
                {sendData.goodsId ? (<Text style={[styles.info]}>今日现货价 {this.unitSymbol}{suggestedPrice || '--'}{this.unit}/吨</Text>) : null}
            </View>
        )
    }

    // 计算毛利-闭口
    calculateProfit = () => {
        if (this.tCode != 'C') return
        let profit = 0;
        let { purchasePrice, salePrice, quantity, priceType } = sendData;
        if (priceType == 2) {
            // 暂定价
            let purchaseUdPrice = this.showData.purchaseUdPrice ? (this.showData.purchaseUdIndex == 0 ? this.showData.purchaseUdPrice : -this.showData.purchaseUdPrice) : 0;
            let saleUdPrice = this.showData.saleUdPrice ? (this.showData.saleUdIndex == 0 ? this.showData.saleUdPrice : -this.showData.saleUdPrice) : 0;
            let totalUdPrice = MethodUtil.countObj.subtract(saleUdPrice, purchaseUdPrice) || 0;
            profit = MethodUtil.countObj.multiply(totalUdPrice, quantity) || 0;
        } else {
            // 一口价
            let total = MethodUtil.countObj.subtract(salePrice, purchasePrice) || 0;
            profit = MethodUtil.countObj.multiply(total, quantity) || 0;
        }
        this.setState({ profit });
    }

    // 升贴水失去焦点
    onBlurUdPrice = (type) => {
        if (!this.showData[type].trim()) this.showData[type] = '0';
        this.setState({ status: 'data' })
    }

    // 升贴水获取焦点
    onFocusUdPrice = (type) => {
        if (this.showData[type] == '0') this.showData[type] = ' ';
        this.setState({ status: 'data' })
    }

    // 一口价/暂定价显示内容
    _renderPrice = () => {
        let { priceType } = sendData;
        return (
            <View style={{ marginBottom: 15 * scale }}>
                <View>
                    {this._renderSwitchWrap()}
                    {
                        priceType == '2' ?
                            (
                                // 非闭口-暂定价
                                <FormItem border keyboardType="numeric" editable={sendData.barePrice ? false : true} type={'input'} label={'暂定价'} rightText={this.unit + '/吨'} value={sendData.barePrice && sendData.barePrice.toString()} placeHolder={'请输入'} handleCallBack={this._getPrice} required />
                            )
                            : (
                                // 非闭口-一口价
                                <FormItem border keyboardType="numeric" editable={sendData.barePrice ? false : true} type={'input'} label={'一口价'} rightText={this.unit + '/吨'} value={sendData.barePrice && sendData.barePrice.toString()} placeHolder={'请输入'} handleCallBack={this._getPrice} required />
                            )
                    }
                    {this._renderTodayPrice()}
                </View>

            </View>
        )
    }

    //溢短装率
    _ydzl = () => {
        let { ysPercent } = sendData;
        console.log('ysPercent-99999', ysPercent)
        if (this.tCode === 'S' || this.tCode === 'C') {
            return <FormItem border onBlurFn={this._validation} keyboardType="numeric" type={'input'} label={'溢短装率'} rightText={'%'} value={ysPercent} placeHolder={'请输入'} handleCallBack={this._ysPercentCallBack} required />
        } else if (this.tCode === 'E' || this.tCode === 'QH') {
            return <FormItem type={'mutiInput'} disable={true} label={'结算公式'} value={ysPercent} editable={false} rightText={"%"} />
        } else {
            return null;
        }
    }

    _validation = () => {
        let { ysPercent } = sendData;
        if (isNaN(ysPercent)) {
            ToastUtil.showWarning('请输入有效数字');
        } else if (ysPercent && (ysPercent < 0 || ysPercent > 20)) {
            ToastUtil.showWarning('请输入大于等于0且小于等于20的数字');
        }
    }

    // 选择基准月（公式）
    _baseSettlCallBack = (index) => {
        sendData.formulaSettleName = this.state.baseSettleData[index].dictName;
        sendData.formulaSettleValue = this.state.baseSettleData[index].dictKey;
        if (sendData.formulaSettleValue == 'CUSTOM_DAY' || sendData.formulaSettleValue == 'CUSTOM_MONTH') { // 是否显示自定义
            this.isCustom = true;
        } else {
            this.isCustom = false;
            sendData.formulaCustomValue = null;
        }
        this.setState({
            baseSettleModal: false,
            baseSettleIndex: index
        })
    }

    //获取基准月
    _getBase = async () => {
        let { priceFormlaId } = sendData;
        if (!priceFormlaId) return;
        let responseData = await HTTP.POST(API_GENERATE(API.NEW_ORDER_SETTLEDETAIL), { formulaId: priceFormlaId });
        if (responseData) {
            sendData.formulaSettleType = responseData.cycleType;
            sendData.baseSettleTitle = this._getBaseSettleTitle(responseData.cycleType);
            if (sendData.formulaSettleType == 'FIXED_DATE_RANGE') {
                sendData.formulaSettleValue = responseData.periodDay;
            }
            this.setState({
                baseSettleData: responseData.detailVOList
            })
        }



    }


    /**
    * 结算方式
    */
    //private String formulaSettleType;
    /**
     * 结算方式值
     */
    //private String formulaSettleValue;

    /**
     * 结算方式自定义值
     */
    //private String formulaCustomValue;

    _getBaseSettleTitle = (strKey) => {
        //BASE_DATE    基准日
        //FIXED_DATE_RANGE  日期范围
        //MONTHLY_AVG  基准月
        let title = '';
        if (strKey == 'BASE_DATE') {
            title = '基准日';
        } else if (strKey == 'MONTHLY_AVG') {
            title = '基准月';
        } else {
            title = '日期范围';
        }
        return title;
    }

    _getYear = () => {
        let arrYear = [];
        for (let i = 2000; i < 2080; i++) {
            arrYear.push(i)
        }
        return arrYear || [];
    }

    //基准日清空
    _clearDay = (dictKey) => {
        sendData.formulaSettleType = null;
        sendData.formulaSettleValue = null;
        sendData.formulaCustomValue = null;
        sendData.formulaSettleName = null;
        sendData.baseSettleTitle = null;
        if (dictKey == '1') { // 如果一口价
            this.isCustom = false;
        }
    }

    _SelectCallBack = (callData) => {
        console.log("checkRebateFlag-callback-aaa-bbb-ccc", callData);
        sendData = OrderCreateMethods._callRebate(callData, sendData);
        console.log("sendData", sendData);
    }

    //原产地-回调
    _addressCallback = (addressData) => {
        console.log("addressData", addressData)
        sendData.makeAreaId = addressData.makeAreaId;
        sendData.makePlace = addressData.makePlace;
        this.setState({
            ls: true
        })
    }

    //原产地 - 关闭弹框
    _closeModal = () => {
        this.setState({
            modalVisible: false
        })
    }


    render() {
        let {
            goodsModal, goodsValue,
            goodsList, goodsListVal, status,
            settlementIndex, settlementData, settlementModal, settlementValue,
            settlementPriceIndex, settlementPriceData, settlementPriceModal, settlementPriceValue,
            quantityAppointModal, quantityAppointData, quantityAppointIndex, quantityAppointValue,
            quantityAppointValueOld, settlementPriceValueOld,
            editable, executeEditable, priceEditable, fixedPriceEditable, includeNextMonth, profit,
            baseSettleIndex, baseSettleModal, baseSettleData, modalVisible
        } = this.state;
        let { priceType, orderType, udPriceOld, checkRebateFlag, rebateId, companyId, makePlace } = sendData;
        let { longQuantity, remainLongQuantity, suggestedPrice, huoIndex, purchaseUdIndex, saleUdIndex, udPrice, purchaseUdPrice, saleUdPrice } = this.showData;
        let ProductSend = [];
        if (sendData.goodsId) {
            ProductSend.push({ goodsId: sendData.goodsId, goodsName: sendData.goodsName, transLevel: sendData.transLevel })
        }
        let month = includeNextMonth ? '下月' : '当月';
        return (
            <KeyboardAvoidingView style={styles.container} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={74}>
                <ScrollView style={styles.scrollWrap} keyboardShouldPersistTaps={'handled'} showsVerticalScrollIndicator={false}>

                    {
                        this.tCode == 'C' ? (
                            <View>
                                <FormItem type={'input'} label={'供应商'} value={sendData.companyNameBuy} editable={false} border />
                                <FormItem type={'input'} label={'客户'} value={sendData.companyName} editable={false} border />
                            </View>
                        ) : (
                                <FormItem type={'input'} label={orderType == 'S' ? '客户' : '供应商'} value={sendData.companyName} editable={false} border />
                            )
                    }

                    <FormItem border type={'select'} label={'商品'} value={goodsValue} placeHolder={'请选择商品'} handleCallBack={this.selectProduct} required />
                    {(this.tCode === 'S' && orderType === "S" && sendData.goodsId && priceType == '1' && companyId) ? <SelectOnffBlock params={{ companyId, goodsId: sendData.goodsId, priceType, longOrderId: this.longFrameIdArr, tCode: this.tCode }} data={{ checkRebateFlag: checkRebateFlag || false, rebateId }} callBack={this._SelectCallBack} /> : null}
                    <View>
                        {/* 采购/销售 总量 */}
                        <FormItem border editable={(this.bidId && this.isCustIntentionPlan == 'Y') ? false : true} keyboardType="numeric" type={'input'} label={this.getQuantityText(`(${month})`)} rightText={'吨'} value={sendData.quantity} placeHolder={'请输入'} handleCallBack={this._allQuantity} required />
                        {/* 商品数量展示 */}
                        <View style={{ paddingLeft: 22 * scale, paddingRight: 22 * scale }}>
                            <Text style={styles.info}>剩余可转单{sendData.remainQuantity || '-'}吨</Text>
                            {sendData.goodsId ? this._renderProductCount() : null}
                        </View>

                        {/* 切换是否含下月采购*/}
                        {
                            (this.tCode == 'S' || this.tCode == 'E') ? (
                                <TouchableOpacity activeOpacity={.8} style={styles.selectWrap} onPress={() => { this.selectNextMonthQuantity() }}>
                                    <Image style={{ marginRight: 4 * scale }} source={includeNextMonth ? checkOnImg : checkOffImg} />
                                    <Text style={includeNextMonth ? { opacity: 1 } : { opacity: .65 }}>使用下月计划量</Text>
                                </TouchableOpacity>
                            ) : null
                        }

                        {/* 下月采购/销售量 */}
                        {
                            // includeNextMonth ? (
                            //   <FormItem border keyboardType="numeric" type={'input'} label={this.getQuantityText('(下月)')} rightText={'吨'} value={sendData.nextQuantity} placeHolder={'请输入'} handleCallBack={this._nextMonthQuantity} required />
                            // ) : null
                        }

                        {/* 商品数量展示 */}
                        {/* <View style={{ paddingLeft: 22 * scale, paddingRight: 22 * scale }}>
                  {
                    includeNextMonth && sendData.goodsId ? (
                      <Text style={styles.info}>下月剩余可采/可销计划量1000.000吨</Text>
                    ) : null
                  }
                </View> */}

                        {/* 一口价和暂定价显示内容 */}
                        {this._renderPrice()}

                        {/* 结算价公式-暂定价 */}
                        {
                            priceType == '2' ? <FormItem disable={settlementPriceValueOld ? true : false} border type={'select'} label={'结算公式'} value={settlementPriceValue} placeHolder={'请选择商品'} handleCallBack={() => { this.openModal({ settlementPriceModal }) }} required /> : null
                        }
                        {/* 升贴水-暂定价 */}
                        {
                            priceType == '2' ? (
                                <View>
                                    <UpDown keyboardType="numeric" editable={udPriceOld ? false : true} unit={this.unit + '/吨'} unitStyle={{ color: '#000', fontSize: 14 * scale }} value={udPrice && udPrice.toString()} selectIndex={huoIndex} callBack={this._upDownFn} onBlurFn={() => { this.onBlurUdPrice('udPrice') }} onFocusFn={() => { this.onFocusUdPrice('udPrice') }} />
                                </View>
                            ) : null
                        }

                        {
                            (!sendData.formulaSettleType || priceType == '1') ? null : (
                                sendData.formulaSettleType == 'FIXED_DATE_RANGE' ? null : <FormItem required border type={'select'} label={sendData.baseSettleTitle} value={sendData.formulaSettleName} placeHolder={'请选择'} handleCallBack={() => { this.openModal({ baseSettleModal }) }} />
                            )
                        }
                        {(this.isCustom || sendData.formulaCustomValue) ? (sendData.formulaSettleType == 'FIXED_DATE_RANGE' ? <FormItem inputStyle={{ width: 190 * scale }} required border type={'input'} disable={true} label={sendData.baseSettleTitle} value={sendData.formulaCustomValue} editable={false} /> : <FormItem type={'select'} label={sendData.formulaSettleType == 'BASE_DATE' ? '自定义日期' : '自定义月份'} value={sendData.formulaCustomValue} placeHolder={'请选择'} handleCallBack={() => { this.DatePicker.show() }} required />) : null}
                        {/* 远期采购说明 */}
                        {
                            this.tCode === 'F' ? (
                                <FormItem border type={'input'} label={sendData.orderType == 'P' ? '远期采购说明' : '远期销售说明'} editable={editable} value={sendData.remark ? sendData.remark + '' : ''} placeHolder={'请输入'} handleCallBack={this._remark} required />
                            ) : null
                        }
                        {/* 品质约定 */}
                        <FormItem border disable={quantityAppointValueOld ? true : false} type={'select'} label={'品质约定'} value={quantityAppointValue} placeHolder={'请选择品质约定'} handleCallBack={() => { this.openModal({ quantityAppointModal }) }} required />

                        {/* 品质说明 品质约定选择'其他'时显示 */}
                        {
                            sendData.qualityStd == '3' ? (
                                <FormItem border type={'input'} label={'品质说明'} editable={editable} value={sendData.qualityRemark} placeHolder={'请输入品质说明'} handleCallBack={this._quantityAppoint} required />
                            ) : null
                        }
                        {/* 溢短装率 */}
                        {this._ydzl()}
                        {/* 原产地 */}
                        <FormItem border type={'select'} label={'原产地'} value={makePlace} placeHolder={'请选择原产地'} handleCallBack={() => { this.openModal({ modalVisible }) }} required />
                    </View>
                </ScrollView>
                <View style={styles.btnWarp}>
                    <Button text={'添加'} width={300} height={34} onPress={this.save} />
                </View>

                {/* 基准日 */}
                {/* <Common type="modal" demoData={(
          <Common type="listRadio" selectIndex={settlementIndex} title="结算基准日期" listData={settlementData} selectCallBack={this._settlementCallBack} />
        )} isVisible={settlementModal} closeCallballFn={() => { this._closeModal({ settlementModal }) }} /> */}

                {/* 选择结算公式 */}
                <Common type="modal" demoData={(
                    <Common type="listRadio" selectIndex={settlementPriceIndex} title="选择结算公式" listData={settlementPriceData} selectCallBack={this._settlementPriceCallBack} />
                )} isVisible={settlementPriceModal} closeCallballFn={() => { this._closeModal({ settlementPriceModal }) }} />

                {/* 选择基准月 */}
                <Common type="modal" demoData={(
                    <Common type="listRadio" selectIndex={baseSettleIndex} title="请选择" listData={baseSettleData} selectCallBack={this._baseSettlCallBack} />
                )} isVisible={baseSettleModal} closeCallballFn={() => { this._closeModal({ baseSettleModal }) }} />
                {/* 基准日弹框 */}

                {/* 选择品质约定 */}
                <Common type="modal" demoData={(
                    <Common type="listRadio" selectIndex={quantityAppointIndex} title="选择品质约定" listData={quantityAppointData} selectCallBack={this._quantityAppointCallBack} />
                )} isVisible={quantityAppointModal} closeCallballFn={() => { this._closeModal({ quantityAppointModal }) }} />

                {/* 商品选择弹窗 */}
                {
                    (sendData.companyId != '' && goodsModal) ? (<ProductSelect
                        confirmPress={this._confirmPress}
                        cancelPress={this._cancelPress}
                        sendData={this._getGoodsParams()}
                        mainCheckData={ProductSend}
                        modalVisible={goodsModal}
                        groupOnoff={this.groupOnoff}
                        tCode={this.tCode} />) : null
                }
                {
                    status != 'data' ? (<View style={styles.statusStyle}><PageStatusIndex status={status} /></View>) : null
                }
                <DatePicker
                    key={new Date().getTime()}
                    column={sendData.formulaSettleType === 'MONTHLY_AVG' ? 2 : false} //代表显示列数
                    HH={false}
                    mm={false}
                    ss={false}
                    unit={['年', '月', '日']}
                    endYear={2080}
                    onPickerConfirm={(valueArr) => {
                        let valueArrNew = [];
                        let valueArrMonth = [];
                        valueArr && valueArr.forEach((item, index) => {
                            let lsItem = item.slice(0, item.length - 1);
                            lsItem = Utils.zeroPadding(lsItem)
                            valueArrNew.push(lsItem);
                            if (index != valueArr.length - 1) {
                                valueArrMonth.push(lsItem);
                            }
                        })
                        if (sendData.formulaSettleType == 'MONTHLY_AVG') { // 基准月
                            sendData.formulaCustomValue = valueArrMonth.join('-');
                            sendData.formulaCustomValue = sendData.formulaCustomValue.substring(0, 7);
                        } else {
                            sendData.formulaCustomValue = valueArrNew.join('-');
                            sendData.formulaCustomValue = sendData.formulaCustomValue.substring(0, 10);
                        }
                        this.setState({ ls: true })
                    }}
                    onPickerCancel={() => {
                        console.log('cancel')
                    }}
                    ref={ref => this.DatePicker = ref} />
                {
                    modalVisible ? <OriginalAddress
                        modalVisible={modalVisible}
                        closeModal={this._closeModal}
                        params={{ tradeType: 'I' }}
                        addressCallback={this._addressCallback}
                    /> : null
                }
            </KeyboardAvoidingView>
        )
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5F5F5',
        paddingLeft: 12 * scale,
        paddingRight: 12 * scale,
    },
    scrollWrap: {
        backgroundColor: '#fff',
        borderRadius: 4 * scale,
    },
    btnWarp: {
        height: 72 * scale,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
    },
    statusStyle: {
        flex: 1,
        position: 'absolute',
        height: '100%',
        width: '100%',
        top: 0,
        left: 12 * scale,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center'
    },
    infoWrap: {
        marginBottom: 8 * scale,
        marginTop: 8 * scale
    },
    info: {
        color: '#F66464',
        fontSize: 13 * scale,
        marginTop: 4 * scale
    },
    selectWrap: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-end',
        paddingTop: 14 * scale,
        paddingBottom: 14 * scale,
        marginRight: 24 * scale,
    },
    switchBtn: {
        marginLeft: 6 * scale,
        marginRight: 6 * scale,
    },
    priceTypeValue: {
        fontSize: 14 * scale,
        color: '#848A96'
    },
    borderWrapBox: {
        position: 'relative',
    },
    borderWrap: {
        borderWidth: 1 * scale,
        borderStyle: 'solid',
        borderColor: '#F5A726',
        marginTop: 20 * scale,
        marginBottom: 2 * scale,
        borderRadius: 4 * scale,
        paddingTop: 10 * scale,
        paddingBottom: 10 * scale,
    },
    borderTips: {
        position: 'absolute',
        backgroundColor: '#fff',
        height: 18 * scale,
        width: 52 * scale,
        lineHeight: 18 * scale,
        textAlign: 'center',
        top: 12 * scale,
        left: 150 * scale,
        fontSize: 13 * scale,
        color: '#F5A726',
        zIndex: 1
    },
    tagIcon: {
        width: 16 * scale,
        height: 16 * scale,
        borderRadius: 8 * scale,
        alignItems: 'center',
        justifyContent: 'center',
        marginRight: 10 * scale,
    }
})